package com.example.content.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.RuntimeException
import java.lang.reflect.ParameterizedType

/**
 * Created by zhudongao
 * Desc
 * Date 2020/9/20
 */
abstract class BaseMvvmFragment<T : ViewDataBinding, VM: ViewModel> : BaseLazyFragment() {
    lateinit var dataBinding: T
    lateinit var viewModel:VM

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //防止fragment嵌套fragment，首层viewpager中的fragment切换，会销毁重建，导致子fragment重建问题
        if (!this::dataBinding.isInitialized) {
            dataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
            dataBinding.lifecycleOwner = this
            viewModel = ViewModelProvider(this).get(getViewModuleClass())
            initView()
            initListener()
        }
        return dataBinding.root
    }

    open fun initListener() {

    }

    override fun onLazyLoad() {
        queryData()
        setBindingData()
        dataBinding.executePendingBindings()
    }

    open fun setBindingData() {

    }

    open fun queryData() {

    }

    open fun initView() {

    }

//    private fun getViewModuleClass(): Class<VM> {
//        val type = javaClass.genericSuperclass
//        if (type is ParameterizedType) {
//            return type.actualTypeArguments[1] as Class<VM>
//        } else {
//            throw RuntimeException("not get The property View Module!")
//        }
//    }

    abstract fun getViewModuleClass() :Class<VM>

    abstract fun getLayoutId(): Int
}